'use strict';

import Lodash from 'lodash';

const option = {
    method: 'POST',
    mode: 'cors',
    cache: 'default',
    credentials: 'include', // 开启cookie支持
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json'
    }
};

const _fetch = async function (url, options, data) {
    let op = Lodash.assign({}, JSON.parse(JSON.stringify(option)), options);
    let mType = op.method;
    switch (mType) {
        case 'POST':
            if (data instanceof window.FormData) { // 上传附件
                op.body = data;
                delete op.headers['Content-Type']; // 上传文件，不需要 Content-Type，设置了反而出错（找不到边界点）
            } else {
                op.body = JSON.stringify(data);
            }
            break;
        case 'GET':
            break;
        default:
            break;
    }
    let response = await fetch(url, op);
    let response1 = response.clone();
    response1.json().then(result=>{
        if(result.state === '10005'){
            router.push('/');
        }
    });
    if(op.type === 'img'){
        return response;
    }
    else{
        return response.json();
    }
};

let Post = function (url, data) {
    let option = { method: 'POST' };
    return _fetch(url, option, data);
};

let Get = function (url, data) {
    let option = { method: 'GET'};
    data = data || {};
    url = formatGetRequestUri(url,data);
    return _fetch(url, option);
};

let GetImg = function (url,data) {
    let option = { method: 'GET', type: 'img'};
    data = data || {};
    url = formatGetRequestUri(url,data);
    return _fetch(url, option);
};

let formatGetRequestUri = function (uri, params) {
    let arr = [];
    for (let p in params) {
        if (params[p] !== '' && params[p] !== null) {
            arr.push([p, '=', params[p]].join(''))
        }
    }
    if (uri.indexOf('?') === -1 && arr.length > 0) {
        uri = uri.concat('?')
    }
    if (arr.length > 0) {
        if (uri.charAt(uri.length - 1) !== '?') {
            uri = uri.concat('&')
        }
        uri = uri.concat(arr.join('&'))
    }
    return uri
};

export default {
    Post, Get, GetImg
};
